package site.entity;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import javax.persistence.Entity;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;

@Entity
@Table(name = "USER", schema = "USERS")
public class User implements UserDetails {

    private Long id;
    private boolean accountNonExpired;
    private boolean accountNonLocked;
    private boolean credentialsNonExpired;
    private String password;
    private String username;
    private Set<UserRole> roles;
    private boolean enabled;

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
    public Set<UserRole> getRoles() {
        return roles;
    }

    @Column(name = "ENABLED")
    public boolean isEnabled() {
        return enabled;
    }

    @Column(name = "PASSWORD")
    public String getPassword() {
        return password;
    }

    @Column(name = "USERNAME")
    public String getUsername() {
        return username;
    }


    @Column(name = "ACCOUNT_NON_EXPIRED")
    public boolean isAccountNonExpired() {
        return accountNonExpired;
    }

    @Column(name = "ACCOUNT_NON_LOCKED")
    public boolean isAccountNonLocked() {
        return accountNonLocked;
    }

    @Column(name = "CREDENTIALS_NON_EXPIRED")
    public boolean isCredentialsNonExpired() {
        return credentialsNonExpired;
    }


    @Transient
    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        // todo optimize.  (for Jan)
        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(roles.size());
        for (GrantedAuthority authority : roles) {
            authorities.add(authority);
        }
        return authorities;
    }


    public void setRoles(final Set<UserRole> roles) {
        this.roles = roles;
    }

    public void setId(final Long id) {
        this.id = id;
    }

    public void setEnabled(final boolean enabled) {
        this.enabled = enabled;
    }

    public void setPassword(final String password) {
        this.password = password;
    }

    public void setUsername(final String username) {
        this.username = username;
    }

    public void setAccountNonExpired(final boolean accountNonExpired) {
        this.accountNonExpired = accountNonExpired;
    }

    public void setAccountNonLocked(final boolean accountNonLocked) {
        this.accountNonLocked = accountNonLocked;
    }

    public void setCredentialsNonExpired(final boolean credentialsNonExpired) {
        this.credentialsNonExpired = credentialsNonExpired;
    }
}
